using System;
using System.Collections.Generic;

namespace MyCollections
{
    public class SortedDictionaryEnumerator<TKey, TValue> where TKey : IComparable<TKey>
    {
        private SortedDictionary<TKey, TValue> _sortedDictionary;
        private Stack<Node<TKey, TValue>> _stack;
        private Node<TKey, TValue> _current;

        public SortedDictionaryEnumerator( SortedDictionary<TKey, TValue> sortedDictionary)
        {
            _sortedDictionary = sortedDictionary;
            _current = null;
            _stack= new Stack<Node<TKey, TValue>>();
            _stack.Clear();
        }

        public KeyValuePair<TKey , TValue> Current
        {
            get { return new KeyValuePair<TKey, TValue>(_current.Key,_current.Value); }
        }

        public bool MoveNext()
        {
            if (_current == null)
            {
                _current = _sortedDictionary.Root;
                while (_current.Left != null)
                {
                    _stack.Push(_current);
                    _current = _current.Left;
                }
                return true;
            }
            
            if (_current.Right != null)
            {
                _current = _current.Right;
                while (_current.Left != null)
                {
                    _stack.Push(_current);
                    _current = _current.Left;
                }
                return true;
            }

            if (_stack.Count > 0)
            {
                _current = _stack.Pop();
                return true;
            }

            return false;
        }

        public void Reset()
        {
            _stack.Clear();
            _current = null;
        }

    }
}